<?php

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;

/**
 * 更新客户状态定时任务
 */
class UpdateCustomerStatus extends Command
{
    protected function configure()
    {
        $this->setName('customer:update-status')
            ->setDescription('更新客户状态');
    }

    protected function execute(Input $input, Output $output)
    {
        $output->writeln('开始更新客户状态...');
        
        try {
            $updateCount = 0;
            
            // 获取所有客户
            $customers = Db::name('customer')
                ->where('is_delete', 0)
                ->field('id,productName,filingTime,mailDate,filingCaseNo,court,courtPhone,executionCaseNo')
                ->select();
                
            foreach ($customers as $customer) {
                $newStatus = $this->calculateCustomerStatus($customer);
                
                // 只有状态发生变化时才更新
                $currentStatus = Db::name('customer')->where('id', $customer['id'])->value('status');
                if ($currentStatus != $newStatus) {
                    Db::name('customer')->where('id', $customer['id'])->update(['status' => $newStatus]);
                    $updateCount++;
                }
            }
            
            $output->writeln("状态更新完成，共更新 {$updateCount} 条记录");
            
        } catch (\Exception $e) {
            $output->writeln('状态更新失败：' . $e->getMessage());
            return 1;
        }
        
        return 0;
    }

    /**
     * 计算客户状态
     * @param array $customer 客户信息
     * @return int 状态值
     */
    private function calculateCustomerStatus($customer)
    {
        $customerId = $customer['id'];
        $productName = $customer['productName'];
        
        // 检查是否为退案
        if (strpos($productName, '退案') !== false) {
            // 检查是否有还款协议
            $hasContract = Db::name('contracts')
                ->where('customer_id', $customerId)
                ->where('status', 1) // 审核通过的协议
                ->count() > 0;
                
            return $hasContract ? 6 : 5; // 退案②：有协议，退案①：无协议
        }
        
        // 检查是否有还款协议
        $hasContract = Db::name('contracts')
            ->where('customer_id', $customerId)
            ->where('status', 1) // 审核通过的协议
            ->count() > 0;
            
        if ($hasContract) {
            // 检查还款是否完结
            $isCompleted = $this->checkPaymentCompleted($customerId);
            return $isCompleted ? 4 : 3; // 已完结：完结，还款中：未完结
        }
        
        // 检查立案相关字段是否都已填写
        $filingFields = [
            'filingTime',      // 立案时间
            'mailDate',        // 邮寄日期（上传/邮寄日期）
            'filingCaseNo',    // 立案案号
            'court',           // 立案法院
            'courtPhone',      // 法院电话
            'executionCaseNo'  // 执行案号
        ];
        
        $filledCount = 0;
        foreach ($filingFields as $field) {
            if (!empty($customer[$field])) {
                $filledCount++;
            }
        }
        
        // 如果6个字段都已填写，则为已立案，否则为进行中
        return ($filledCount === 6) ? 2 : 1;
    }

    /**
     * 检查还款是否完结
     * @param int $customerId 客户ID
     * @return bool
     */
    private function checkPaymentCompleted($customerId)
    {
        // 获取该客户的所有还款协议
        $contracts = Db::name('contracts')
            ->where('customer_id', $customerId)
            ->where('status', 1) // 审核通过
            ->field('id,amount')
            ->select();
            
        if (empty($contracts)) {
            return false;
        }
        
        foreach ($contracts as $contract) {
            $contractId = $contract['id'];
            $totalAmount = $contract['amount'];
            
            // 计算该协议的已还款总额
            $paidAmount = Db::name('payment_record')
                ->where('contract_id', $contractId)
                ->where('is_delete', 0)
                ->sum('amount') ?: 0;
                
            // 如果有任何一个协议未完结，则整体未完结
            if ($paidAmount < $totalAmount) {
                return false;
            }
        }
        
        return true;
    }
} 